package com.cuijq.ms.observer.v7;

import com.google.common.util.concurrent.MoreExecutors;
import java.util.List;
import java.util.concurrent.Executor;

/**
 * @author by CuiJQ
 * @Classname EventBus
 * @Description EventBus Description
 * @Date 2021/5/28 16:26
 */
public class EventBus {

  private Executor executor;
  private ObserverRegistry registry = new ObserverRegistry();

  public EventBus() {
    this(MoreExecutors.directExecutor());
  }

  protected EventBus(Executor executor) {
    this.executor = executor;
  }

  /**
   * register() 函数用来注册观察者
   * @param object
   */
  public void register(Object object) {
    registry.register(object);
  }

  /**
   * 用来给观察者发送消息
   * @param event
   */
  public void post(Object event) {
    List<ObserverAction> observerActions = registry.getMatchedObserverActions(event);
    for (ObserverAction observerAction : observerActions) {
      executor.execute(new Runnable() {
        @Override
        public void run() {
          observerAction.execute(event);
        }
      });
    }
  }
}
